<template>
    <div class="container">
        <div class="header-actions">
            <el-button type="primary" class="createBtn" @click="createRow">新增</el-button>

            <div class="search-form">
                <el-input v-model="searchTitle" placeholder="请输入标题搜索" clearable>
                    <template #append>
                        <el-button @click="searchData">搜索</el-button>
                    </template>
                </el-input>
            </div>
        </div>

        <el-table :data="tableData.data" style="width: 100%;margin-top: 20px;">
            <el-table-column v-for="(model, index) in tableDataDetail" :prop="model.field" :label="model.name"
                :key="index">
                <template #default="scope">
                    <div v-if="model.field === 'imageUrl'">
                        <el-image :src="scope.row[model.field]" alt="Image"
                            style="width: 60px; height: 60px; object-fit: cover;"
                            :preview-src-list="[scope.row[model.field]]"
                            fit="cover">
                            <template #error>
                                <div class="image-error">
                                    <el-icon><picture-filled /></el-icon>
                                    <div class="error-text">加载失败</div>
                                </div>
                            </template>
                        </el-image>
                    </div>
                    <div v-else-if="model.field === 'isPinned'">
                        <el-tag :type="scope.row[model.field] ? 'success' : 'info'">
                            {{ scope.row[model.field] ? '已置顶' : '未置顶' }}
                        </el-tag>
                    </div>
                    <div v-else>
                        {{ scope.row[model.field] }}
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
                <template #default="scope">
                    <el-button size="small" @click="writeRow(scope.$index)">编辑</el-button>
                    <el-button size="small" type="danger" @click="deleteRow(scope.$index)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination background layout="prev, pager, next" :total="total" :page-size="pageSize"
            :current-page="currentPage" @current-change="handlePageChange" @size-change="handlePageSizeChange"
            style="margin-top: 20px;" />

        <!-- 创建数据表单 -->
        <div v-if="isCreate" class="modal-form">
            <div class="modal-content">
                <h3 class="modal-title">新增媒体报道</h3>
                <div class="form-items">
                    <div class="form-item" v-for="(item, index) in CreateDataDetail.data" :key="index">
                        <label>{{ item.name }}</label>
                        <el-upload v-if="item.field === 'image'"
                            class="upload-demo"
                            action="http://localhost:9090/api/upload/image"
                            :on-success="handleUploadSuccess"
                            :before-upload="beforeUpload"
                            :show-file-list="false">
                            <el-button type="primary">点击上传</el-button>
                            <div v-if="item.value" style="margin-top: 10px;">
                                <el-image :src="item.value" style="width: 60px; height: 60px;" />
                            </div>
                            <template #tip>
                                <div class="el-upload__tip">只能上传jpg/png文件</div>
                            </template>
                        </el-upload>
                        <el-switch v-else-if="item.field === 'isPinned'"
                            v-model="item.value"
                            active-text="置顶"
                            inactive-text="不置顶">
                        </el-switch>
                        <el-input v-else :placeholder="item.name" v-model="item.value" clearable></el-input>
                    </div>
                </div>
                <div class="modal-footer">
                    <el-button @click="createRow">取消</el-button>
                    <el-button type="primary" @click="realyCreate">确认</el-button>
                </div>
            </div>
        </div>

        <!-- 修改数据表单 -->
        <div v-if="isWrite" class="modal-form">
            <div class="modal-content edit-modal">
                <div class="modal-header">
                    <h3 class="modal-title">修改媒体报道</h3>
                    <el-button class="close-btn" @click="writeRow(null)" circle>
                        <el-icon><close /></el-icon>
                    </el-button>
                </div>
                <el-divider />
                <div class="form-items">
                    <div class="form-item" v-for="(item, index) in ruleForm.data" :key="index">
                        <label class="form-label">{{ item.name }}</label>
                        <el-upload v-if="item.field === 'image'"
                            class="upload-demo"
                            action="http://localhost:9090/api/upload/image"
                            :on-success="handleUploadSuccess"
                            :before-upload="beforeUpload"
                            :show-file-list="false">
                            <div class="upload-area">
                                <div v-if="item.value" class="preview-image">
                                    <el-image :src="item.value" fit="cover" style="width: 60px; height: 60px;" />
                                    <div class="image-overlay">
                                        <el-icon><upload-filled /></el-icon>
                                        <span>更换图片</span>
                                    </div>
                                </div>
                                <el-button v-else type="primary" class="upload-btn">
                                    <el-icon><plus /></el-icon>
                                    <span>上传图片</span>
                                </el-button>
                            </div>
                            <template #tip>
                                <div class="el-upload__tip">支持 jpg/png 格式，大小不超过 2MB</div>
                            </template>
                        </el-upload>
                        <el-switch v-else-if="item.field === 'isPinned'"
                            v-model="item.value"
                            active-text="置顶"
                            inactive-text="不置顶"
                            class="custom-switch">
                        </el-switch>
                        <el-input v-else :placeholder="item.name" v-model="item.value" clearable
                            :disabled="item.name === '编号'"
                            class="custom-input">
                        </el-input>
                    </div>
                </div>
                <div class="modal-footer">
                    <el-button @click="writeRow(null)" plain>取消</el-button>
                    <el-button type="primary" @click="realyWrite">保存修改</el-button>
                </div>
            </div>
        </div>

    </div>
</template>

<script setup lang="ts">
    import { reactive, ref } from 'vue';
    import axios from 'axios';
    import { ElMessage } from 'element-plus'
    import { PictureFilled, Close, Plus, UploadFilled } from '@element-plus/icons-vue'

    const MAX_PINNED_COUNT = 3 // 最大置顶数量限制
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    const searchTitle = ref('')

    const tableDataDetail = reactive([
        { field: 'id', name: '编号' },
        { field: 'title', name: '标题' },
        { field: 'content', name: '内容' },
        { field: 'imageUrl', name: '图片' },
        { field: 'isPinned', name: '置顶' }
    ])

    const tableData = reactive({ data: [] })

    const handlePageChange = (page: number) => {
        currentPage.value = page
        fetchTableData()
    }

    const handlePageSizeChange = (size: number) => {
        pageSize.value = size
        fetchTableData()
    }

    function fetchTableData() {
        axios.get('http://localhost:9090/api/mediea/all').then((res) => {
            tableData.data = res.data
            total.value = res.data.length
        }).catch(error => {
            ElMessage.error('加载数据失败')
        })
    }

    // 获取当前已置顶的数量
    function getPinnedCount() {
        return tableData.data.filter(item => item.isPinned).length
    }

    function searchData() {
        if (!searchTitle.value) {
            fetchTableData()
            return
        }
        
        axios.post('http://localhost:9090/api/mediea/search', {
            title: searchTitle.value
        }).then((res) => {
            if (res.data) {
                tableData.data = res.data
                total.value = res.data.length
            } else {
                tableData.data = []
                total.value = 0
                ElMessage.warning('未找到相关数据')
            }
        }).catch(() => {
            ElMessage.error('搜索失败')
        })
    }

    fetchTableData()

    function deleteRow(index: number) {
        const id = tableData.data[index].id
        axios.delete(`http://localhost:9090/api/mediea/${id}`).then(() => {
            fetchTableData()
            ElMessage.success('删除成功')
        }).catch(() => {
            ElMessage.error('删除失败')
        })
    }

    const CreateDataDetail = reactive({
        data: [
            { value: '', field: 'title', name: '标题' },
            { value: '', field: 'content', name: '内容' },
            { value: '', field: 'image', name: '图片' },
            { value: false, field: 'isPinned', name: '置顶' }
        ]
    })

    const isCreate = ref(false)

    function createRow() {
        isCreate.value = !isCreate.value
        // 重置表单数据
        if (!isCreate.value) {
            CreateDataDetail.data.forEach(item => {
                item.value = item.field === 'isPinned' ? false : ''
            })
        }
    }

    function handleUploadSuccess(response: any, uploadFile: any) {
        const imageUrl = "http://localhost:9090/api/upload/uploads/" + response
        
        // 根据当前操作的表单更新图片值
        if (isCreate.value) {
            const imageField = CreateDataDetail.data.find(item => item.field === 'image')
            if (imageField) {
                imageField.value = imageUrl
            }
        } else if (isWrite.value) {
            const imageField = ruleForm.data.find(item => item.field === 'image')
            if (imageField) {
                imageField.value = imageUrl
            }
        }
        
        ElMessage.success('图片上传成功')
    }

    function beforeUpload(file: File) {
        const isImage = file.type.startsWith('image/')
        const isLt2M = file.size / 1024 / 1024 < 2

        if (!isImage) {
            ElMessage.error('只能上传图片文件!')
            return false
        }
        if (!isLt2M) {
            ElMessage.error('图片大小不能超过 2MB!')
            return false
        }
        return true
    }

    function realyCreate() {
        const data = {
            title: CreateDataDetail.data.find(item => item.field === 'title')?.value,
            content: CreateDataDetail.data.find(item => item.field === 'content')?.value,
            imageUrl: CreateDataDetail.data.find(item => item.field === 'image')?.value,
            isPinned: CreateDataDetail.data.find(item => item.field === 'isPinned')?.value
        }

        if (!data.title || !data.content || !data.imageUrl) {
            ElMessage.warning('请填写完整信息')
            return
        }

        // 检查置顶数量限制
        if (data.isPinned && getPinnedCount() >= MAX_PINNED_COUNT) {
            ElMessage.error(`最多只能置顶${MAX_PINNED_COUNT}个媒体报道`)
            return
        }

        axios.post('http://localhost:9090/api/mediea/', data).then(() => {
            fetchTableData()
            isCreate.value = false
            ElMessage.success('新增成功')
        }).catch(() => {
            ElMessage.error('新增失败')
        })
    }

    const isWrite = ref(false)
    const ruleForm = reactive({
        id: null,
        data: [
            { value: '', field: 'id', name: '编号' },
            { value: '', field: 'title', name: '标题' },
            { value: '', field: 'content', name: '内容' },
            { value: '', field: 'image', name: '图片' },
            { value: false, field: 'isPinned', name: '置顶' }
        ]
    })

    function writeRow(index: number | null) {
        if (index !== null) {
            const item = tableData.data[index]
            ruleForm.id = item.id
            ruleForm.data.forEach(field => {
                if (field.field === 'image') {
                    field.value = item['imageUrl'] // 修正字段名
                } else {
                    field.value = item[field.field]
                }
            })
            isWrite.value = true
        } else {
            isWrite.value = false
        }
    }

    function realyWrite() {
        const data = {
            id: ruleForm.id,
            title: ruleForm.data.find(item => item.field === 'title')?.value,
            content: ruleForm.data.find(item => item.field === 'content')?.value,
            imageUrl: ruleForm.data.find(item => item.field === 'image')?.value,
            isPinned: ruleForm.data.find(item => item.field === 'isPinned')?.value
        }

        if (!data.title || !data.content || !data.imageUrl) {
            ElMessage.warning('请填写完整信息')
            return
        }

        // 检查是否修改了置顶状态
        const originalItem = tableData.data.find(item => item.id === data.id)
        const isNewPinned = data.isPinned && !originalItem.isPinned

        // 如果是新置顶且已达到最大置顶数，则拒绝操作
        if (isNewPinned && getPinnedCount() >= MAX_PINNED_COUNT) {
            ElMessage.error(`最多只能置顶${MAX_PINNED_COUNT}个媒体报道`)
            return
        }

        axios.put(`http://localhost:9090/api/mediea/${data.id}`, data).then(() => {
            fetchTableData()
            isWrite.value = false
            ElMessage.success('修改成功')
        }).catch(() => {
            ElMessage.error('修改失败')
        })
    }
</script>


<style scoped>
    .container {
        padding: 20px;
    }

    .header-actions {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
    }

    .search-form {
        width: 300px;
    }

    .modal-form {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.5);
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 999;
    }

    .modal-content {
        background: white;
        padding: 30px;
        border-radius: 12px;
        width: 600px;
        overflow: visible;
    }

    .modal-title {
        text-align: center;
        margin-bottom: 20px;
        font-size: 18px;
        color: #333;
    }

    .form-items {
        margin-bottom: 20px;
    }

    .form-item {
        margin-bottom: 15px;
    }

    .form-item label {
        display: block;
        margin-bottom: 8px;
        color: #606266;
    }

    .modal-footer {
        display: flex;
        justify-content: center;
        gap: 20px;
        margin-top: 30px;
    }

    .el-pagination {
        display: flex;
        justify-content: center;
    }

    .el-pagination .el-pager li.is-active {
        background-color: #409EFF;
        color: white;
    }
</style>